package org.example.cors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.annotation.WebFilter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义 servlet 过滤器全局设置跨域请求，与 {@link InfoController#postInfo} 完全同理，只是提升为全局设置
 * * 标准 Servlet 过滤器，实现 javax.servlet.Filter 接口，并重现它的 3 个方法
 * * filterName：表示过滤器名称，可以不写
 * * value：配置请求过滤的规则，如 "/*" 表示过滤所有请求，包括静态资源，如 "/user/*" 表示 /user 开头的所有请求
 *
 * @author wangMaoXiong
 * @version 1.0
 * @date 2021/6/6 10:02
 */
@WebFilter(filterName = "MyCorsFilter", value = {"/*"})
public class MyCorsFilter implements Filter {

    private static final Logger log = LoggerFactory.getLogger(MyCorsFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("com.wmx.servlet.SystemFilter -- 系统启动...");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        //转为 HttpServletRequest 输出请求路径
        HttpServletRequest request = (HttpServletRequest) req;
        String queryString = request.getQueryString();
        log.info("com.wmx.servlet.SystemFilter -- 过滤器放行前...." + request.getRequestURL() + "?" + queryString);

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");

        filterChain.doFilter(req, res);
        log.info("com.wmx.servlet.SystemFilter -- 过滤器返回后...." + request.getRequestURL() + "?" + queryString);
    }

    @Override
    public void destroy() {
        log.info("com.wmx.servlet.SystemFilter -- 系统关闭...");
    }

}